package org.yscz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yscz.entity.Scale;
import org.yscz.entity.ScaleType;
import org.yscz.entity.vo.ScaleTypeVo;
import org.yscz.mapper.ScaleMapper;
import org.yscz.mapper.ScaleTypeMapper;
import org.yscz.service.ScaleTypeService;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author muqs
 * @create 2021-08-18 17:48
 */
@Service
@Slf4j
public class ScaleTypeServiceImpl implements ScaleTypeService {

    @Autowired
    private ScaleTypeMapper scaleTypeMapper;

    @Autowired
    private ScaleMapper scaleMapper;

    @Override
    public ScaleType add(ScaleType scaleType) {
        scaleType.setUpdateTime(new Date());
        scaleTypeMapper.insert(scaleType);
        return scaleType;
    }

    @Override
    public void modify(ScaleType scaleType) {
        scaleType.setUpdateTime(new Date());
        scaleTypeMapper.updateById(scaleType);
    }

    @Override
    public void del(Long scaleTypeId) {

        ScaleType scaleType = scaleTypeMapper.selectById(scaleTypeId);
        if (scaleType != null) {
            if (!"默认".equals(scaleType.getScaleTypeName())) {
                scaleTypeMapper.deleteById(scaleTypeId);

                // 将改量表分类下的量表数据改为"默认"分类
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("scale_type_name", "默认");
                ScaleType defaultScaleType = scaleTypeMapper.selectOne(queryWrapper);

                Scale scale = new Scale();
                scale.setScaleTypeIdFk(defaultScaleType.getScaleTypeId());
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("scale_type_id_fk", scaleTypeId);
                scaleMapper.update(scale, updateWrapper);
            } else {
                log.info("【默认】量表分类不允许删除");
                return;
            }
        }
    }

    @Override
    public IPage<ScaleType> listPage(QueryWrapper queryWrapper, IPage<ScaleType> page) {
        return scaleTypeMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<ScaleType> list(QueryWrapper queryWrapper) {
        return scaleTypeMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<ScaleType> listPageByCondition(IPage<ScaleTypeVo> page, Map condition) {
        return scaleTypeMapper.listPageByCondition(page, condition);
    }
}
